package com.zhangtai.modules.controller.admin;




import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.zhangtai.common.annotation.SysAuthorityLog;
import com.zhangtai.config.AsyncMethod;
import com.zhangtai.consts.CommonConstr;
import com.zhangtai.enums.ErrCodeEnum;
import com.zhangtai.modules.constVo.NoticeConst;
import com.zhangtai.modules.controller.aouthLogin.LoginController;
import com.zhangtai.modules.dao.ImgUrlDao;
import com.zhangtai.modules.entity.common.ImgUrlEntity;
import com.zhangtai.modules.entity.common.MailRecordEntity;
import com.zhangtai.modules.entity.employee.EmployeeInfoEntity;
import com.zhangtai.modules.entity.employee.EmployeeRecruitmentEntity;
import com.zhangtai.modules.service.common.MailRecordService;
import com.zhangtai.modules.service.employee.EmployeeInfoService;
import com.zhangtai.modules.service.employee.EmployeeRecruitmentService;
import com.zhangtai.modules.vo.MailVo;
import com.zhangtai.utils.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.*;

import javax.mail.MessagingException;
import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @Author: ming
 * @Date: 2020/6/5 0005 下午 3:19
 */
@RestController
@Api(tags="通用接口")
@RequestMapping("common")
@Slf4j
public class CommonController {

//    @Value("${uploadFileServerPathPrefix}")
//    String path ;
    @Autowired
    private EmailUtil emailUtil;
    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private AsyncMethod asyncMethod;
    @Autowired
    private MailRecordService mailRecordService;
    @Autowired
    private EmployeeInfoService employeeInfoService;
    @Autowired
    private LoginController loginController;
    @Autowired
    private NoticeController noticeController;
    @Autowired
    private ImgUrlDao imgUrlDao;
    @Autowired
    private EmployeeRecruitmentService employeeRecruitmentService;





    @PostMapping("/sendMail")
    @ApiOperation(value="发送邮件")
    @SysAuthorityLog(value = "发送邮件")
    public R sendMail(@RequestBody @Valid MailVo mailVo,HttpServletRequest request) throws Exception {
        String content = mailVo.getContent();
        String receive = mailVo.getReceive();
        String subject = mailVo.getSubject();


        JSONObject data = loginController.getUserInfo(request).getData();
        if (ObjectUtils.isEmpty(data)){
            return R.error("用户未登录");
        }
        String name = data.getString("name"); //管理员姓名
        Long sendOid = data.getLong("id");
        mailVo.setSendOid(sendOid);
        String text=null;
        if (StringUtils.isEmpty(receive )){
            return R.error("收件人不能为空");
        }
        if (StringUtils.isEmpty(subject)){
            return R.error("主题不能为空");
        }
        if (StringUtils.isEmpty(content)){
           text=subject;

        }else {
            text=content;
        }
        List<String> url = mailVo.getUrl();
        if (CollectionUtils.isEmpty(url)){
            return R.error("附件为空或者上传时间太短，请重新上传");
        }
//        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        String ip = request.getRemoteAddr();


//        使用redis计数器限制次数  ,60分钟内发送对象超过10次
        redisTemplate.boundValueOps(receive ).increment(1);
        redisTemplate.expire(receive ,30, TimeUnit.MINUTES);
        Integer i = TypeCastUtils.toInt(redisTemplate.boundValueOps(receive ).get());

//                       使用redis计数器限制次数  ,60分钟内发送超过200次
        redisTemplate.boundValueOps(ip).increment(1);
        redisTemplate.expire(ip,30, TimeUnit.MINUTES);
        Integer j = TypeCastUtils.toInt(redisTemplate.boundValueOps(ip).get());
        System.out.println(i);
        if (i>=20||j>=100){
            return R.error("操作太频繁，请30分钟后重新发送");
        }
        List<String> urls = mailVo.getUrl();
        if (CollectionUtils.isEmpty(urls)){
            try {
                //            不带附件
                emailUtil.sendHtml(receive ,subject,text);
            } catch (MessagingException e) {
                e.printStackTrace();
                log.error("邮件发送失败",e);
                return R.error(505,"邮件发送失败");
            }

            try {

                EmployeeInfoEntity employeeInfoEntity = new EmployeeInfoEntity();
                employeeInfoEntity.setOid(mailVo.getOid());
                employeeInfoEntity.setIsOffer(1); //标志为已发送
//                employeeInfoEntity.setStatus(5);//标志为已发送
                employeeInfoService.updateByIdE(employeeInfoEntity);
                //修改招聘录用状态
                EmployeeInfoEntity entity= employeeInfoService.getByIdE(employeeInfoEntity.getOid());
                if(!org.springframework.util.StringUtils.isEmpty(entity.getRecruitmentId())){
                    EmployeeRecruitmentEntity employeeRecruitmentEntity=  new EmployeeRecruitmentEntity();
                    employeeRecruitmentEntity.setId(entity.getRecruitmentId());
                    employeeRecruitmentEntity.setIsOffer(1); //标志为已发送
                    employeeRecruitmentService.updateByIdE(employeeRecruitmentEntity);
                }

                asyncMethod.saveMailLog(mailVo,1,name); //发送成功
                //offer发送待办完成
                noticeController.updateNoticeTodo(mailVo.getOid(), NoticeConst.TODO_TYPE_OFFER_SEND);
            } catch (MessagingException e) {
                asyncMethod.saveMailLog(mailVo,2,name); //发送失败
                e.printStackTrace();
                log.error("邮件记录保存失败",e);
                return R.error("邮件记录保存失败");

            }

        }else {
            try {
                //            带附件
                emailUtil.sendHtmlAttachmentList(receive,subject,content,urls);  //发送带附件邮件
            } catch (MessagingException e) {
                e.printStackTrace();
                log.error("邮件发送失败:{}",e);
                return R.error(ErrCodeEnum.MAIL_FAIL);
            }

            try {

                EmployeeInfoEntity employeeInfoEntity = new EmployeeInfoEntity();
                employeeInfoEntity.setOid(mailVo.getOid());
                employeeInfoEntity.setIsOffer(1);
//                employeeInfoEntity.setStatus(5);
                employeeInfoService.updateByIdE(employeeInfoEntity);

                //修改招聘录用状态
                EmployeeInfoEntity entity= employeeInfoService.getByIdE(employeeInfoEntity.getOid());
                if(!org.springframework.util.StringUtils.isEmpty(entity.getRecruitmentId())){
                    EmployeeRecruitmentEntity employeeRecruitmentEntity=  new EmployeeRecruitmentEntity();
                    employeeRecruitmentEntity.setId(entity.getRecruitmentId());
                    employeeRecruitmentEntity.setIsOffer(1); //标志为已发送
                    employeeRecruitmentService.updateByIdE(employeeRecruitmentEntity);
                }

                asyncMethod.saveMailLog(mailVo,1,name); //发送成功
                //offer发送待办完成
                noticeController.updateNoticeTodo(mailVo.getOid(), NoticeConst.TODO_TYPE_OFFER_SEND);
            } catch (MessagingException e) {
                asyncMethod.saveMailLog(mailVo,2,name); //发送失败
                e.printStackTrace();
                log.error("邮件记录保存错误:{}",e);
                return R.error("邮件记录保存失败");
//                throw new RException("邮件发送失败",e);
            }

        }
        return R.ok();
    }




    @GetMapping("/getMailLog")
    @ApiOperation(value="分页查询邮件发送记录")
//    @PreAuthorize("hasAuthority('sys:email:get')")
    public R<PageResult<MailRecordEntity>> getMailLog(@RequestParam(value = "name",required = false) String name,
            @RequestParam(value = "sendName",required = false)String sendName,
            @RequestParam(value = "receive",required = false)String receive,
            @ApiParam(value="1:发送成功，2：发送失败",required=false) @RequestParam(value = "status", required = false) Integer status,
            @RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum,
                        @RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize,
                                                      HttpServletRequest request) throws Exception{
//        R checkR = loginController.checkOrgPermission(request,null,false);
//        if(!R.isOk.equals(checkR.getStatus())){
//            return checkR;
//        }
        JSONObject data = loginController.getUserInfo(request).getData();
        if (ObjectUtils.isEmpty(data)){
            return R.error("用户未登录");
        }
//        List<Long> orgIds = (List<Long>) checkR.getData();
        Long oid = data.getLong("id");
        PageResult<MailRecordEntity> pageResult=null;
        JSONArray authorities = data.getJSONArray("authorities");
        List<String> list = JSON.parseObject(authorities.toJSONString(), List.class);
//        如果有邮件权限则查看所有
        if (list.contains("sys:mail:all")){
            pageResult = mailRecordService.queryPage(name,sendName,receive,status,null, pageNum, pageSize);
        }else {
           pageResult = mailRecordService.queryPage(name,sendName,receive,status,oid, pageNum, pageSize);
        }


        return R.ok(pageResult);
    }




    @GetMapping("/getTokenByOid/{oid}")
    @ApiOperation(value="获取token")
    public R<String> getTokenByOid(@PathVariable Long oid){
        EmployeeInfoEntity employeeInfoEntity = employeeInfoService.getByIdE(oid);
        if (ObjectUtils.isEmpty(employeeInfoEntity)){
            return R.error("查询员工为空");
        }
        String token = employeeInfoEntity.getToken();
        redisTemplate.boundValueOps(token).set(CommonConstr.EMP_TOKEN);
        return R.error(token);

    }


    @GetMapping(value="/qrimage")
    @ApiOperation(value="生成二维码接口")
//    @SysAuthorityLog(value = "生成二维码接口")
    public R<String> getQRImage(@RequestParam("url") String url) {
        String s = QrCodeUtils.creatRrCode(url, 360, 360);
        return R.ok(s);
    }


    @GetMapping("/sendAesId")
    @ApiOperation(value="根据员工id返回加密的AES key")
    public R getAesKeyEmpId(@RequestParam("id") String id) throws Exception {
        Calendar cal = Calendar.getInstance();
        String key = cal.get(Calendar.YEAR)+"000000000000";
        String code = AESUtil.aesEncrypt(id, key);
        return  R.ok(code);

    }

    public String getFileUrls(List<String> fileUrls,Long oid,String name){
        String url = "";
        if(!CollectionUtils.isEmpty(fileUrls)){
            int i = 1;
            for(String fileUrl:fileUrls){
                ImgUrlEntity urlEntity = imgUrlDao.selectOne(new QueryWrapper<ImgUrlEntity>().
                        eq("oid",oid).eq("url",fileUrl).
                        eq("is_delete",0).eq("type",11));
                if(ObjectUtils.isEmpty(urlEntity)){
                    urlEntity = new ImgUrlEntity();
                    urlEntity.setUrl(fileUrl);
                    urlEntity.setName(name);
                    urlEntity.setCreateTime(new Date());
                    urlEntity.setOid(oid);
                    urlEntity.setType(11);
                    imgUrlDao.insert(urlEntity);
                }

                if(i==fileUrls.size()){
                    url +=fileUrl;
                }else{
                    url += fileUrl+",";
                }
                i++;
            }
        }
        return url;
    }
}
